import cv2
import time
import ColorDetect


def test_camera_open_time():
    """测试摄像头打开耗时"""
    print("=" * 50)
    print("测试摄像头打开耗时...")

    start_time = time.time()
    # cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 0表示默认摄像头cv2.CAP_V4L2
    cap = cv2.VideoCapture(0, cv2.CAP_V4L2)  # 0表示默认摄像头cv2.CAP_DSHOW

    if cap.isOpened():
        end_time = time.time()
        open_time = end_time - start_time
        print(f"摄像头打开成功，耗时: {open_time:.4f} 秒")
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

        # 读取一帧测试
        ret, frame = cap.read()
        if ret:
            print(f"摄像头分辨率: {frame.shape[1]}x{frame.shape[0]}")

        cap.release()
        return open_time
    else:
        print("摄像头打开失败！")
        return None


def test_image_read_time():
    """测试读取图片耗时"""
    print("=" * 50)
    print(f"测试读取耗时:")

    # cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 0表示默认摄像头cv2.CAP_V4L2
    cap = cv2.VideoCapture(0, cv2.CAP_V4L2)  # 0表示默认摄像头cv2.CAP_DSHOW
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    start_time = time.time()
    ret, image = cap.read()
    end_time = time.time()

    if ret:
        read_time = end_time - start_time
        print(f"图片读取成功，耗时: {read_time:.4f} 秒")
        print(f"图片尺寸: {image.shape[1]}x{image.shape[0]}")
        print(f"图片通道数: {image.shape[2]}")
        return read_time, image
    else:
        print("图片读取失败！")
        return None, None


def test_camera_frame_processing():
    """测试摄像头实时处理帧的耗时"""
    print("=" * 50)
    print("测试摄像头实时处理...")

    # cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 0表示默认摄像头cv2.CAP_V4L2
    cap = cv2.VideoCapture(0, cv2.CAP_V4L2)  # 0表示默认摄像头cv2.CAP_DSHOW
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    if not cap.isOpened():
        print("无法打开摄像头！")
        return

    frame_count = 0
    total_read_time = 0
    total_process_time = 0

    print("按 'q' 键退出实时测试...")

    while True:
        # 测试读取帧的耗时
        start_read = time.time()
        ret, frame = cap.read()
        end_read = time.time()

        if not ret:
            break

        read_time = end_read - start_read

        # 测试处理帧的耗时
        start_process = time.time()
        zb, processed_frame = ColorDetect.get_center(frame, "green")
        end_process = time.time()

        process_time = end_process - start_process

        # 累计统计
        frame_count += 1
        total_read_time += read_time
        total_process_time += process_time

        # # 显示结果
        # cv2.imshow('Original', frame)
        # cv2.imshow('Processed', processed_frame)

        # 每10帧输出一次统计信息
        if frame_count % 10 == 0:
            avg_read = total_read_time / frame_count
            avg_process = total_process_time / frame_count
            fps = 1.0 / (avg_read + avg_process)
            print(f"帧数: {frame_count}, 平均读取耗时: {avg_read:.4f}s, "
                  f"平均处理耗时: {avg_process:.4f}s, 估计FPS: {fps:.2f}")

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

    if frame_count > 0:
        print(f"\n实时处理统计:")
        print(f"总帧数: {frame_count}")
        print(f"平均读取耗时: {total_read_time / frame_count:.4f} 秒")
        print(f"平均处理耗时: {total_process_time / frame_count:.4f} 秒")
        print(f"平均总耗时: {(total_read_time + total_process_time) / frame_count:.4f} 秒")


def main():
    """主函数"""
    print("OpenCV 性能测试程序")
    print("=" * 50)

    # 1. 测试摄像头打开耗时
    camera_open_time = test_camera_open_time()

    read_time, image = test_image_read_time()

    test_camera_frame_processing()
if __name__ == "__main__":
    main()